package me.lwn.auth.resources;

import me.lwn.auth.application.UserManager;
import me.lwn.auth.common.HttpMsg;
import me.lwn.auth.resources.cmd.ChangePassword;
import me.lwn.auth.resources.cmd.ForgetPassword;
import me.lwn.auth.resources.cmd.ResetPassword;
import me.lwn.auth.security.utils.LocalMessageSource;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("password")
public class PasswordController {

    private final UserManager userManager;
    private final MessageSourceAccessor message = LocalMessageSource.getAccessor();

    public PasswordController(UserManager userManager) {
        this.userManager = userManager;
    }

    /**
     * 用户端修改密码
     *
     * @param changePassword 修改密码
     */
    @PostMapping("change")
    public HttpMsg<String> changePassword(@RequestBody ChangePassword changePassword) {
        userManager.changePassword(changePassword);
        return HttpMsg.success(message.getMessage("PasswordController.forgetPasswordSuccess"));
    }

    /**
     * 管理员后台重置密码
     *
     * @param resetPassword 重置密码
     */
    @PostMapping("reset")
    public HttpMsg<String> resetPassword(@RequestBody ResetPassword resetPassword) {
        userManager.resetPassword(resetPassword);
        return HttpMsg.success(message.getMessage("PasswordController.forgetPasswordSuccess"));
    }

    /**
     * 忘记密码
     *
     * @param forgetPassword 忘记密码对象
     */
    @PostMapping("forget")
    public HttpMsg<String> forgetPassword(@RequestBody ForgetPassword forgetPassword) {
        userManager.forget(forgetPassword.getMobile(), forgetPassword.getCode(), forgetPassword.getPlainPassword());
        return HttpMsg.success(message.getMessage("PasswordController.forgetPasswordSuccess"));
    }
}
